package org.hot100.h022;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author yu
 * @Date 2022/3/6
 */
public class Solution {

    public static void main(String[] args) {

        Solution solution = new Solution();
        System.out.println(solution.generateParenthesis(3));

    }

    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();

        if (n == 0) {
            return list;
        }

        build4("", n, n, list);
        return list;
    }

    /**
     * 递归拼接个数
     *
     * @param str 拼接字符串
     * @param left 左括号个数
     * @param right 右括号个数
     * @param res 结果
     */
    public void build(String str, int left, int right, List<String> res) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }

        // 剪枝（如图，左括号可以使用的个数严格大于右括号可以使用的个数，才剪枝，注意这个细节）
        if (left > right) {
            return;
        }

        // 拼接左括号
        if (left > 0) {
            build(str + "(", left - 1, right, res);
        }

        // 拼接右括号
        if (right > 0) {
            build(str + ")", left, right - 1, res);
        }

    }

    public void build2(String str, int left, int right, List<String> res) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }

        if (left > right) {
            return;
        }

        if (left > 0) {
            build2(str + "(", left - 1, right, res);
        }

        if (right > 0) {
            build2(str + ")", left, right - 1, res);
        }

    }

    public void build3(String str, int left, int right, List<String> res) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }

        if (left > right) {
            return;
        }

        if (left > 0) {
            build3(str + "(", left - 1, right, res);
        }
        if (right > 0) {
            build3(str + ")", left, right - 1, res);
        }
    }

    public void build4(String str, int left, int right, List<String> res) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }

        if (left > right) {
            return;
        }
        if (left > 0) {
            build4(str + "(", left - 1, right, res);
        }
        if (right > 0) {
            build4(str + ")", left, right - 1, res);
        }
    }
}
